/* eslint-disable guard-for-in */
/* eslint-disable @typescript-eslint/prefer-for-of */
/* eslint-disable no-param-reassign */
// import { console.log } from "../../app/xw";

export namespace Utils {
    /**
     * return [min,max)
     */
    export function getRandom(min: number, max: number): number {
        let rnd = Math.random();
        let ex = Math.floor(min + rnd * (max - min));
        return ex;
    }

    export function getNumberFormatStr(value) {
        let valueStr = value;
        if (value < 10) {
            valueStr = "0" + value;
        }
        return valueStr;
    }

    export function getNumDescWithSign(value: number) {
        if (value > 0) {
            return cc.js.formatStr("+%s", value);
        } else if (value < 0) {
            return value.toString();
        } else {
            return "0";
        }
    }

    export function isNumbers(str: string) {
        let reg = /^[0-9]+.?[0-9]*$/;
        if (reg.test(str)) {
            return true;
        }
        return false;
    }

    export function checkInputNumber(str: string, min, max) {
        if (str.length == 0) {
            return false;
        }
        let a = parseInt(str, 10);
        if (a >= min && a <= max) {
            return true;
        } else {
            return false;
        }
    }

    export function RGBA2Color(r, g, b, a: number = 255) {
        let result = parseInt(((r << 16) | (g << 8) | b).toString(16), 16);
        return result;
    }

    export function formatBytes(bytes) {
        let name = ["B", "KB", "MB", "GB", "TB", "PB"];
        let pos = 0;
        while (bytes >= 1204) {
            bytes /= 1024;
            pos++;
        }
        return bytes.toFixed(2) + " " + name[pos];
    }

    export function findDeep(node: cc.Node, nodeName: string): cc.Node {
        if (node.name == nodeName) return node;
        for (let i = 0; i < node.children.length; i++) {
            let res = findDeep(node.children[i], nodeName);
            if (res) return res;
        }
        return null;
    }

    export function numCutDown(num: number, dotRightNum: number = 1) {
        if (num < 9999) return num;
        num = num / 10000;
        let n1 = num.toFixed(dotRightNum + 1);
        let n2 = n1.substring(0, n1.length - 1);
        let result = cc.js.formatStr("%s万", n2);
        return result;
    }

    export function dateFormat(fmt: string, date: Date) {
        let ret;
        const opt = {
            "Y+": date.getFullYear().toString(), // 年
            "m+": (date.getMonth() + 1).toString(), // 月
            "d+": date.getDate().toString(), // 日
            "H+": date.getHours().toString(), // 时
            "M+": date.getMinutes().toString(), // 分
            "S+": date.getSeconds().toString(), // 秒
            // 有其他格式化字符需求可以继续添加，必须转化成字符串
        };
        for (let k in opt) {
            ret = new RegExp("(" + k + ")").exec(fmt);
            if (ret) {
                fmt = fmt.replace(ret[1], ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0"));
            }
        }
        return fmt;
    }

    export function formatSeconds(value: number) {
        let result = value;
        let h = Math.floor(result / 3600) < 10 ? "0" + Math.floor(result / 3600) : Math.floor(result / 3600);
        let m = Math.floor((result / 60) % 60) < 10 ? "0" + Math.floor((result / 60) % 60) : Math.floor((result / 60) % 60);
        let s = Math.floor(result % 60) < 10 ? "0" + Math.floor(result % 60) : Math.floor(result % 60);

        let res = "";
        if (h !== "00") res += `${h}时`;
        if (m !== "00") res += `${m}分`;
        res += `${s}秒`;
        return res;
    }

    /**
     * 获取指定时间的时间戳
     * @param month date.getMonth()
     */
    export function getTimeStamp(year: number, month: number, day: number, h: number, m: number, s: number) {
        return new Date(`${year}-${month + 1}-${day} ${h}:${m}:${s}`).getTime();
    }

    export function isPhoneFun(phones) {
        let myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
        if (!myreg.test(phones)) {
            console.log("手机号格式不正确");
            return false;
        } else {
            console.log("手机号格式正确");
            return true;
        }
    }

    export function IsCard(str) {
        let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        return reg.test(str);
    }

    export function isStringOnlyHasChineseAndLetter(s) {
        let regu = "^[a-zA-Z\u4e00-\u9fa5]+$";
        let re = new RegExp(regu);
        if (re.test(s)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 简单的对象深拷贝
     * 由此可以看出，虽然此方法确实可以复制object和array对象，并且进行了深复制，却无法复制function
     * @param obj
     * @returns
     */
    export function simpleDeepClone(obj) {
        return JSON.parse(JSON.stringify(obj));
    }

    // 获取对象的长度 移植代码
    export function getTableLen(tbl) {
        if (tbl == null || typeof tbl != "object") {
            return 0;
        }
        let count = 0;
        for (let k in tbl) {
            count++;
        }
        return count;
    }

    export function clipLabel(label: cc.Label, str: string, _maxWidth: number, extStr?: string) {
        _maxWidth = _maxWidth ?? 0;
        extStr = extStr ?? "...";
        if (!!label && !!str) {
            str = String(str);
            let maxWidth = str.length;
            label.string = str;
            // @ts-ignore
            label._forceUpdateRenderData();
            while (label.node.width > _maxWidth) {
                label.string = str.substring(0, maxWidth) + extStr;
                // @ts-ignore
                label._forceUpdateRenderData(true);
                maxWidth--;
                if (maxWidth <= 0) break;
            }
        }
    }
    /**
     * 获取当前场景的脚本，脚本需要是挂在Canvas下面的且Canvas不能改名，否则获取不到。
     * @param type 脚本名
     * @returns 脚本对象，可能为null
     */
    export function getRunningSceneScript<T extends cc.Component>(type: { prototype: T }): T {
        if (cc?.director?.getScene()) {
            let _curScene = cc.director.getScene();
            return _curScene?.getChildByName("Canvas")?.getComponent(type);
        }
        return null;
    }

    export function isClickPixelAlpha(sprite: cc.Sprite, x, y) {}
    /* 新增截取字符串的方法避免乱码
        @param name 字符串  num 截取的字符串长度  isNotByteNum 是不是以字节截取长度
        @return str
    */
    export function splitStrName(name: string, num: number, isNotByteNum: boolean) {
        if (!isNotByteNum) {
            name = String(name);
            let recordByte = 0;
            let byteNum = 0;
            let len = name.length;
            for (let i = 0; i < len; i++) {
                let c = name.charAt(i);
                byteNum += Utils.haveUnicodeNum(c) == 1 ? 2 : 1;
                if (recordByte == 0 && byteNum >= num) recordByte = i;
            }
            let str = "";
            if (num >= byteNum) str = name.substr(0, len);
            else str = name.substr(0, recordByte + 1) + "...";
            return decodeURI(str);
        } else {
            let len = name.length;
            let str = "";
            if (len <= num) str = name.substr(0, len);
            else str = name.substr(0, num) + "...";
            // return unescape(str);
            return decodeURI(str);
        }
    }
    export function haveUnicodeNum(str: string) {
        let isUnicode = encodeURI(str).indexOf("%u") >= 0 ? 1 : 0;
        return isUnicode;
    }

    export function obj2String(o) {
        if (!(o instanceof Object)) {
            console.log(o);
            return;
        }
        console.log(JSON.stringify(o));
    }

    export function isValueInValid(val: any) {
        return val == undefined || val == null;
    }

    export function isValueValid(val: any) {
        return val != undefined && val != null;
    }

    export function isTimeInSection(startTime: string, endTime: string, date?: Date) {
        if (!date) {
            date = new Date();
        }
        let curTimeStr = Utils.dateFormat("YYYYmmddHHMMSS", date);
        let inSection = curTimeStr >= startTime && curTimeStr <= endTime;
        console.log("isTimeInSection beginTime", startTime);
        console.log("isTimeInSection endTime", endTime);
        console.log("isTimeInSection date", date);
        console.log("isTimeInSection curTimeStr inSection", curTimeStr, inSection);
        return inSection;
    }
}
